<?php

namespace App\Console\Commands\Cruise;

use App\Models\Common\ResourcesModel;
use App\Models\Cruise\CruiseProjectCategoryModel;
use App\Models\Cruise\CruiseTaskProjectModel;
use App\Models\Cruise\CruiseTemplateModel;
use App\Models\Cruise\CruiseTemplatePositionModel;
use App\Models\Cruise\CruiseTemplatePositionProjectMappingModel;
use Illuminate\Console\Command;
use Illuminate\Support\Str;
use Kuafu\File\FileUtil;

class ExportConfigDB extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'cruise:export-config-db';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '导出本次cruise相关配置表';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        // 需要注意的表 project_category/project/template/template_position/template_position_project_mapping
        $projectCategoryId = 537;
//        $projectId         = 533; // TODO
        $templateId        = 441;

        $unsetTimestamp = function ($item) {
            $item->timestamps = false;
            unset($item->createdByUid, $item->updatedByUid);
            return $item;
        };

        // 1. project_category
        $categorys = CruiseProjectCategoryModel::query()
                                               ->where('id', '>=', $projectCategoryId)
                                               ->get()
                                               ->map($unsetTimestamp);

        $projects = CruiseTaskProjectModel::query()
//                                          ->where('id', '>=', $projectId)
                                          ->whereIn('categoryId', $categorys->pluck('id'))
                                          ->get()
                                          ->map($unsetTimestamp);

        $templates = CruiseTemplateModel::query()
                                        ->where('id', '>=', $templateId)
                                        ->get()
                                        ->map($unsetTimestamp);

        $resources = ResourcesModel::query()
                                   ->where('module', ResourcesModel::MODULE_TYPE_CRUISE)
                                   ->where('business', ResourcesModel::BUSINESS_CRUISE_PROJECT_TIPS)
                                   ->whereIn('businessId', $templates->pluck('id'))
                                   ->get()
                                   ->map($unsetTimestamp)
                                   ->map(function ($item) {
                                       unset($item->id);
                                       return $item;
                                   });


        $templatePositions = CruiseTemplatePositionModel::query()
                                                        ->whereIn('templateId', $templates->pluck('id'))
                                                        ->get()
                                                        ->map($unsetTimestamp);

        $templatePositionMappings = CruiseTemplatePositionProjectMappingModel::query()
                                                                             ->whereIn('templateId',
                                                                                 $templates->pluck('id'))
                                                                             ->get()
                                                                             ->map($unsetTimestamp)
                                                                             ->map(function ($item
                                                                             ) {
                                                                                 unset($item->id);
                                                                                 return $item;
                                                                             });

        $arr = [
            (new CruiseProjectCategoryModel)->getTable()                => $categorys->toArray(),
            (new CruiseTaskProjectModel)->getTable()                    => $projects->toArray(),
            (new CruiseTemplateModel)->getTable()                       => $templates->toArray(),
            (new ResourcesModel)->getTable()                            => $resources->toArray(),
            (new CruiseTemplatePositionModel)->getTable()               => $templatePositions->toArray(),
            (new CruiseTemplatePositionProjectMappingModel)->getTable() => $templatePositionMappings->toArray(),
        ];

        $json = json_encode($arr, JSON_UNESCAPED_UNICODE);

        // 上传至oss，返回url
        // UTF8的BOM头
        $path = sys_get_temp_dir() . '/' . Str::random() . '.json';
        $fd   = fopen($path, 'w+');
        fwrite($fd, $json);
        fclose($fd);

        $objectName = "tmp/" . date('Ymd') . "/" . Str::random() . "/cruise_config_db.json";

        $streamUrl = FileUtil::uploadFile($path, 'json', $objectName)['url'];
        dump($streamUrl);

        @unlink($path);
    }
}
